var fs = require('fs');
var path = require('path');
const _ = require('lodash');

const utils = require('./utils');
const StaticServer = require('./server');
const { uploadFile } = require('./utils/upload');

items = {};

module.exports = function(router) {
  return router
    // 首页
    // .get('/manage', async function (ctx, next) {
    //   await ctx.render('main.html');
    // })
    // 上传文件
    .post('/upload', async function (ctx, next) {
      let serverFilePath = path.join(__dirname, '../files');
      
      const result = await uploadFile( ctx, {
        fileType: 'album', // common or album
        path: serverFilePath
      });
      ctx.body = {
        fileName: result.meta.fileName
      };
    })
    // 删除资源
    .delete('/delete/:id', async (ctx, next) => {
      const result = {};
      try {
        await utils.deleteFilesById(ctx.params.id);
        result.info = 'ok';
        result.status = 0;
      } catch(err) {
        console.error(err);
        result.info = 'delete error';
      } finally {
        ctx.body = result;
      }
    })
    // 解压文件    
    .get('/extract/:id', async (ctx, next) => {
      let result = {};
      try {
        await extractFileToDir(ctx.params.id);
        result.info = 'extract completed';
        result.status = 0;
      } catch (err)  {
        result.info = err.message;        
      } finally {
        ctx.body = result;
        await next();
      }
    })
    // 获取资源信息（zip文件以及解压缩的文件夹）
    .get('/files', async (ctx, next) => {
      items = {};
      const WWWDIR = path.join(__dirname, '/../www')
      const fileList = await utils.readdir(path.join(__dirname, '/../files'))
        .then(files => files.filter(file => utils.canExtract(file)));
      // 获取静态服务器列表
      const servers = StaticServer.prototype.servers;

      for (let i = 0; i < fileList.length; i++) {
        const fileName = fileList[i];
        const detail = await utils.getFileDetail(path.join(__dirname + '/../files', fileName))
        items[fileName] = {
          file: fileName,
          hasDir: utils.isFileAccessableSync(path.join(WWWDIR, fileName)),
          port: servers[fileName] ? servers[fileName].port : -1,
          detail,
        };
      }
      ctx.body = {
        status: 0,
        fileInfos: [],
        items,
      };
      await next();
    })
    
    // 启动指定id的server，启动服务之前，文件已被解压
    .get('/start/:id', async (ctx, next) => {
      const result = {};
      let filesPath;
      ctx.body = {
        status:0
      }
      let serverFilePath = path.join(__dirname, '../www', ctx.params.id);
      try {
        const staticServer = new StaticServer(serverFilePath);
        // staticServer.start(filesPath.split(/[\\\/]+/).pop());
        const servers = StaticServer.prototype.servers;
        result.status = 0;
        if (servers[serverFilePath]) {
          result.info = 'server is already running';
        } else {
          await staticServer.start();
          result.info = 'ok';
        }
      } catch (err) {
        console.error(err);
        throw err;
      }
      ctx.body = result;

      await next();
    })
    /**
     * 关闭服务
     */
    .delete('/close/:id', async (ctx, next) => {
      const currentServer = StaticServer.prototype.servers[ctx.params.id];
      if (currentServer) {
        currentServer.shutdown();
        ctx.body = {
          status: 0,
        };
      } else {
        ctx.body = {
          status: 501,
          info: '服务器已经停止运行',
        };
      }
      
      await next();
    })
}

/**
 * 通过zipId解压缩zip到指定文件夹
 * @param {String} zipId 
 */
async function extractFileToDir(zipId) {
  const zipFilePath = path.join(__dirname, '../files', zipId);
  // Step.1 判断文件是否可读
  try {
    await utils.isFileAccessable(zipFilePath);
  } catch (err) {
    throw new Error(`${zipId} 不存在`);
  }
  // Step.2 解压文件到指定目录，并获取解压后的目录名（压缩包中的根文件夹）
  let dirName;
  try{
    await utils.extractFile(zipFilePath, path.join(__dirname, '../www', zipId));
  } catch (err) {
    throw new Error('extract error')
  }
}
